import sys
from PySide6.QtCore import Qt
from PySide6.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, 
                              QWidget, QLabel, QPushButton, QFileDialog,
                              QComboBox, QHBoxLayout, QMessageBox, QSlider, QDoubleSpinBox)
from PySide6.QtGui import QPixmap
from src.core.converter import ImageConverter
from src.utils import utils

class ImageFormatConverter(QMainWindow):
    """图片格式转换器主窗口"""
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("图片格式转换器")
        self.setGeometry(100, 100, 600, 400)
        
        # 设置应用图标
        self.set_app_icon()
        
        # 启用拖拽功能
        self.setAcceptDrops(True)
        
        # 初始化UI
        self.init_ui()
        self.converter = ImageConverter()
        
    def set_app_icon(self):
        """设置应用图标（根据操作系统选择对应格式）
        
        根据当前操作系统自动选择对应的图标文件：
        - Windows: 使用 icon.ico
        - macOS: 使用 icon.icns  
        - Linux: 使用 icon.png
        """
        import os
        import platform
        
        # 获取图标目录
        icons_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'assets', 'icons')
        
        # 根据操作系统选择图标格式
        icon_formats = {
            "Windows": "icon.ico",
            "Darwin": "icon.icns",  # macOS
            "Linux": "icon.png"
        }
        
        system = platform.system()
        icon_filename = icon_formats.get(system, "icon.ico")
        icon_path = os.path.join(icons_dir, icon_filename)
        
        if os.path.exists(icon_path):
            from PySide6.QtGui import QIcon
            self.setWindowIcon(QIcon(icon_path))
            print(f"✓ 已设置{system}图标: {icon_filename}")
        else:
            print(f"提示: 未找到 {icon_filename}，使用默认图标")
        
    def init_ui(self):
        """初始化用户界面"""
        main_widget = QWidget()
        layout = QVBoxLayout()
        
        # 文件选择区域
        file_layout = QHBoxLayout()
        self.file_label = QLabel("未选择文件")
        select_btn = QPushButton("选择图片")
        select_btn.clicked.connect(self.select_image)
        file_layout.addWidget(self.file_label)
        file_layout.addWidget(select_btn)
        
        # 分类选择区域
        category_layout = QHBoxLayout()
        category_layout.addWidget(QLabel("格式分类:"))
        self.category_combo = QComboBox()
        categories = ImageConverter.get_categories()
        self.category_combo.addItems(categories)
        self.category_combo.currentTextChanged.connect(self.update_format_combo)
        category_layout.addWidget(self.category_combo)

        # 格式选择区域
        format_layout = QHBoxLayout()
        format_layout.addWidget(QLabel("目标格式:"))
        self.format_combo = QComboBox()
        # 根据默认分类加载格式
        self.update_format_combo(categories[0])
        format_layout.addWidget(self.format_combo)
        
        # 质量调节区域
        quality_layout = QHBoxLayout()
        quality_layout.addWidget(QLabel("质量:"))
        self.quality_slider = QSlider(Qt.Horizontal)  # 水平滑块
        self.quality_slider.setRange(10, 100)
        self.quality_slider.setValue(95)
        self.quality_label = QLabel("95%")
        self.quality_slider.valueChanged.connect(
            lambda v: self.quality_label.setText(f"{v}%")
        )
        quality_layout.addWidget(self.quality_slider)
        quality_layout.addWidget(self.quality_label)
        
        # 文件大小限制区域
        size_layout = QHBoxLayout()
        size_layout.addWidget(QLabel("最大大小(MB):"))
        self.size_spinbox = QDoubleSpinBox()
        self.size_spinbox.setRange(0.1, 10)
        self.size_spinbox.setValue(0)
        self.size_spinbox.setSpecialValueText("无限制")
        size_layout.addWidget(self.size_spinbox)
        
        # 转换按钮
        convert_btn = QPushButton("转换并保存")
        convert_btn.clicked.connect(self.convert_image)
        
        # 图片预览区域
        self.preview_label = QLabel()
        self.preview_label.setFixedSize(400, 300)
        
        # 组装主布局
        layout.addLayout(file_layout)
        layout.addLayout(category_layout)
        layout.addLayout(format_layout)
        layout.addLayout(quality_layout)
        layout.addLayout(size_layout)
        layout.addWidget(convert_btn)
        layout.addWidget(self.preview_label)
        
        main_widget.setLayout(layout)
        self.setCentralWidget(main_widget)
    
    def dragEnterEvent(self, event):
        """拖拽进入事件"""
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
    
    def dropEvent(self, event):
        """拖放处理"""
        urls = event.mimeData().urls()
        if urls:
            file_path = urls[0].toLocalFile()
            self.handle_image_file(file_path)
    
    def select_image(self):
        """选择图片文件"""
        # 动态生成支持的文件过滤器
        supported_extensions = [f"*.{ext}" for ext in ImageConverter.get_supported_formats()]
        file_filter = f"图片文件 ({' '.join(supported_extensions)})"
        
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择图片", "", 
            file_filter
        )
        if file_path:
            self.handle_image_file(file_path)
    
    def handle_image_file(self, file_path):
        """处理图片文件"""
        self.file_label.setText(file_path)
        pixmap = QPixmap(file_path)
        self.preview_label.setPixmap(pixmap.scaled(
            self.preview_label.size(),
            Qt.KeepAspectRatio,  # 保持宽高比
            Qt.SmoothTransformation  # 平滑缩放
        ))

    def update_format_combo(self, category):
        """根据选择的分类更新格式下拉框"""
        self.format_combo.clear()
        formats_dict = ImageConverter.get_formats_by_category(category)
        
        # 创建格式显示文本（包含描述）
        format_items = []
        for ext, desc in formats_dict.items():
            format_items.append(f"{ext.upper()} - {desc}")
        
        self.format_combo.addItems(format_items)
        
        # 设置常用格式的默认值
        default_formats = {'常用格式': 'JPG', '游戏开发': 'DDS', '专业软件': 'PSD', 
                          '科学图像': 'FITS', '传统格式': 'PCX', '文档格式': 'PDF'}
        
        target_format = default_formats.get(category, 'JPG')
        for i, item in enumerate(format_items):
            if item.startswith(target_format):
                self.format_combo.setCurrentIndex(i)
                break
    
    def convert_image(self):
        """转换图片格式"""
        source_path = self.file_label.text()
        if source_path == "未选择文件":
            QMessageBox.warning(self, "警告", "请先选择图片文件")
            return
            
        # 验证源文件
        is_valid, msg = utils.validate_image_file(source_path)
        if not is_valid:
            QMessageBox.critical(self, "错误", f"无效的图片文件: {msg}")
            return
            
        # 从格式描述中提取扩展名
        format_text = self.format_combo.currentText()
        target_format = format_text.split(' - ')[0].lower()
        
        # 使用原文件名作为默认文件名
        import os
        source_dir = os.path.dirname(source_path)
        source_name = os.path.splitext(os.path.basename(source_path))[0]
        default_filename = f"{source_name}.{target_format}"
        
        save_path, _ = QFileDialog.getSaveFileName(
            self, "保存图片", 
            os.path.join(source_dir, default_filename),
            f"{target_format.upper()}文件 (*.{target_format})"
        )
        
        if save_path:
            try:
                quality = self.quality_slider.value()
                max_size = self.size_spinbox.value() if self.size_spinbox.value() > 0 else None
                self.converter.convert(
                    source_path, 
                    save_path, 
                    target_format,
                    quality=quality,
                    max_size_mb=max_size
                )
                QMessageBox.information(self, "成功", "图片转换完成!")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"转换失败: {str(e)}")

    @classmethod
    def run(cls):
        """运行应用程序"""
        app = QApplication(sys.argv)
        window = cls()
        window.show()
        sys.exit(app.exec())
